package com.sofwin.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.realm.Realm;

import com.sofwin.pojo.SUser;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;

public class UserRealm2 implements Realm {
	
	private UserService userService;
	
	private RoleService roleService;

	@Override
	public String getName() {
		return "userRealm";
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 身份认证
	 */
	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName=null;
		String pwd=null;
		try {
			userName = token.getPrincipal().toString();
			pwd = token.getCredentials().toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SUser user = new SUser();
		user.setUserName(userName);
		SUser user2 = userService.selectUserByUserNameAndPwd(user);
		user.setPwd(pwd);
		SUser user3 = userService.selectUserByUserNameAndPwd(user);
		if(user2==null) {
			throw new UnknownAccountException();
		}
		if(user3==null) {
			throw new IncorrectCredentialsException();
		}
		
		return new SimpleAuthenticationInfo(userName,pwd,"userReal");
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

}
